package com.jing.yao.config.filter;

import com.jing.yao.config.threadlocal.ThreadLocalStore;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.TimeZone;

/**
 * 国际化过滤器
 * @author Yao
 * @since 2020-07-03
 */
public class I18nFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取存放TimeZone的ThreadLocal
        ThreadLocal<TimeZone> timeZoneThreadLocal = ThreadLocalStore.timeZoneThreadLocal;

        String timeZone = request.getHeader("Time-Zone");
        if(StringUtils.isNotBlank(timeZone)) {
            timeZoneThreadLocal.set(TimeZone.getTimeZone(timeZone));
        }
        filterChain.doFilter(request, response);
        //清空timeZoneThreadLocal，防止内存泄露
        timeZoneThreadLocal.remove();
    }
}
